#!/usr/bin/env python

import component
import resource.string.app as r

from ..._console import Console

class Sweeper(Console):

    def run(self):
        self.greeting(r)
        
        if self.isRunning(r.name):
            self.info('%s is already running.\n' % r.name)
            self.info('Please wait a moment and try again.\n')
        else:
            alinco = self.loadAlinco()
            if alinco:
                self.sweep(alinco)
                alinco.close()
            
        self.farewell()
        
    def testBulk(self):
        import model
        measurement = model.Measurement()
        measurement.device = 1
        measurement.host = self._args.host
        for i in range(1, 9):
            channel = component.Namespace()
            channel.sequence = i
            channel.value = i
            measurement.channels.append(channel)
        self.info('Save data device %d to server.\n' % measurement.device)
        measurement.bulk()
        
    def loadAlinco(self):
        port = self._args.port
        self.verbose('Serial Port: %s' % port)
        
        baudrate = self._args.baudrate
        self.verbose('Serial Port Baudrate: %s' % baudrate)
        
        try:
            timeout = self._args.timeout
            alinco = component.Alinco(port, baudrate, timeout=timeout)
        except:
            alinco = None
            self.verbose('Error creating serial port instance.\n')
        else:
            self.verbose('Serial port instance created.\n')
        return alinco

    def sweep(self, alinco):
        for device in self._args.devices:
            self.progress('Sweeping device %d... ' % device)
            
            alinco.flush()
            measurements = alinco.flare(device)
            if measurements:
                self.success('OK ^_^\n')
                s = 'Save data device %d to server...\n'
                for measurement in measurements:
                    self.info(s % measurement.device)
                    measurement.bulk(self._args.host)
                    self.success('OK ^_^\n')
            else:
                self.fail('Error >_<\n')

